# Utility.
from compiler import parse as parse_code
from random import choice
from cStringIO import StringIO
from pdb import set_trace as debug
from sys import exc_info as getSystemException

class Configuration:
    def __init__(self, **kwd):
        self.__dict__.update(kwd)

class ServerConfiguration(Configuration):
    address = '127.0.0.1'
    port = 5000
    wgetbin = 'wget'

def create_random_name(length, characters):
    return ''.join(choice(characters) for x in xrange(length))

def parse_safe_string(string):
    'Evaluate string encoded in python syntax (but nothing else).'

    try: return parse_code(string).doc
    except SyntaxError:
        pass

def create_download_request(url, name, **kwd):
    # Todo: build multi-download request.  Here??
    buf = StringIO()

    print >> buf, '[%s]' % (name or '?')
    print >> buf, 'url: %s' % url

    for (n, v) in kwd.iteritems():
        if v is not None:
            print >> buf, '%s: %r' % (n, v)

    return buf.getvalue()

def reraise(exc = (None, None, None)):
    (type, value, tb) = exc
    if value is None:
        (type, value, tb) = getSystemException()

    raise (type, value, tb)

# Debugging.
def evaluate(ns_locals, source):
    '''
    Evaluate python code directly within (RPC) server!
    '''

    ##    global lastSourceCode
    ##    lastSourceCode = source

    if not source.strip():
        return ''

    try: code = compile(source, '<web>', 'single')
    except SyntaxError, e:
        return e.args

    import __main__ as main
    ns_globals = main.__dict__

    from cStringIO import StringIO as newBuffer
    output = newBuffer()

    import sys
    stdout = sys.stdout
    stderr = sys.stderr
    sys.stdout = output
    sys.stderr = output

    # Todo: redirect stdin

    try: exec code in ns_globals, ns_locals
    except:
        from traceback import print_exc
        print_exc()

    finally:
        sys.stdout = stdout
        sys.stderr = stderr

    return output.getvalue()
